package com.erp.module.storesRequisitionPackage

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.os.Handler
import android.os.Message
import android.view.View
import android.widget.AdapterView
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import com.erp.CaptureActivity
import com.erp.Interface.OnUserDataInterface
import com.erp.Myapp
import com.erp.R
import com.erp.mclass.UnCeHandler
import com.erp.module.YuliaoPrint.FragmengtYuliaoPrintLabel
import com.erp.myAdapter.ArrayAdapter
import com.erp.myFragment.BaseKFragment
import com.erp.permission.PermissionListener
import com.erp.util.JsonUtil
import com.erp.util.LanYaUtil
import com.erp.util.Myutil
import com.erp.util.PermissionUtils
import com.example.tsc.tscdll_test.TSCActivity
import kotlinx.android.synthetic.main.activity_cailiao_zhiliang.SpChuLi
import kotlinx.android.synthetic.main.dialog_lanya_shezhi.LeftBt
import kotlinx.android.synthetic.main.dialog_lanya_shezhi.RightBt
import kotlinx.android.synthetic.main.dialog_lanya_shezhi1.SpLanYa
import kotlinx.android.synthetic.main.fragment_srp.BtShengchengPcode
import kotlinx.android.synthetic.main.fragment_srp.IvScan
import kotlinx.android.synthetic.main.fragment_srp.LvCode
import kotlinx.android.synthetic.main.fragment_srp.LvScan
import kotlinx.android.synthetic.main.fragment_srp.ivShezhi
import org.json.JSONException
import org.json.JSONObject

class FragmentSrp : BaseKFragment(), View.OnClickListener, AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener {

    private val f = "FragmentSrp"
    var model = SrpModel()
    var lanya = "34:81:F4:CB:1D:11"
    lateinit var scanList: MutableList<String>
    lateinit var codeList: MutableList<String>
    lateinit var scanAdapter: ArrayAdapter<String>
    lateinit var codeAdapter: ArrayAdapter<String>
    lateinit var updatedialog: AlertDialog
    override fun getLayoutId(): Int {
        fragmentname = f
        return R.layout.fragment_srp
    }

    override fun initData() {
        scanList = ArrayList()
        codeList = ArrayList()
        scanAdapter = ArrayAdapter(activity, R.layout.simple_at_item, scanList)
        codeAdapter = ArrayAdapter(activity, R.layout.simple_at_item, codeList)
        LvScan.adapter = scanAdapter
        LvScan.onItemLongClickListener = this
        LvCode.adapter = codeAdapter
        LvCode.onItemClickListener = this
        IvScan.setOnClickListener(this)
        ivShezhi.setOnClickListener(this)
        BtShengchengPcode.setOnClickListener(this)
        gethuancun()
        var ly = sp.getString("Srplanya", "")
        if (ly != null && ly != "") {
            lanya = ly;
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            IvScan -> {
                PermissionUtils.issaomiao(activity!!, object : PermissionListener {
                    override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                        val intent = Intent()
                        var a = activity
                        if (a != null) {
                            intent.setClass(a, CaptureActivity::class.java)
                            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                            startActivityForResult(intent, 1)
                        }

                    }

                    override fun onFailed(requestCode: Int, deniedPermissions: List<String>) =
                            Myutil.MyTost("没有权限，无法扫描")
                })
            }

            BtShengchengPcode -> {
                setP()
            }

            ivShezhi -> {
                var c = context;
                if (c != null) {
                    val dialog = AlertDialog.Builder(c).create()
                    dialog.setView(EditText(context))
                    dialog.show()
                    dialog.setContentView(R.layout.dialog_lanya_shezhi1)
                    val LanYaAdapter = ArrayAdapter(context, R.layout.lv_sp_tvitem, Myutil.ly_names())
                    dialog.SpLanYa.adapter = LanYaAdapter
                    dialog.SpLanYa.setSelection(LanYaUtil.ly_id(lanya))
                    val window = dialog.window
                    val p = window?.attributes // 获取对话框当前的参数值
                    p?.width = (sp.getInt("width", 0) * 0.9).toInt() // 宽度设置为屏幕的0.65
                    window?.attributes = p
                    dialog.LeftBt.setOnClickListener {
                        lanya = LanYaUtil.ly_address(dialog.SpLanYa.selectedItem.toString())
                        editor.putString("Srplanya", lanya)
                        editor.commit()
                        Myutil.MyTost("打印机切换成功")
                    }
                    dialog.RightBt.setOnClickListener {
                        dialog.dismiss()
                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        UnCeHandler.buzhou = "onActivityResult"
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                1 -> {
                    val bundle = data.extras
                    val s = bundle?.get("result") as String
                    if (!scanList.contains(s)) {
                        scanList.add(s)
                        scanAdapter.notifyDataSetChanged()
                    }
                }
            }
        }
    }

    /**获取生成的条码缓存*/
    fun gethuancun() {
        var data = sp.getString("codeList", "")
        if (data != "" && data != null) {
            var list = data.split("&")
            for (item in list) {
                codeList.add(item)
            }
            codeAdapter.notifyDataSetChanged()
        }
    }

    /**缓存生成的条码*/
    fun edithuancun() {
        var data = "";
        for (i in 0 until codeList.size) {
            if (i >= 10) {
                break
            }
            if (data != "") {
                data += "&"
            }
            data += codeList[i]
        }
        editor.putString("codeList", data)
        editor.commit()
    }

    fun setP() {
        if (scanList.isEmpty()) {
            Myutil.MyTost("未扫描标签")
            return
        }
        updatedialog = Myutil.showupdatedialog(context, "正在上传数据", false)
        model.setPcakage(context!!, scanList, object : OnUserDataInterface {
            override fun onUserData(data: String?) {
                Myutil.Mylog("getDuihao", data)
                updatedialog!!.dismiss()
                CodeJson(data!!)
            }

            override fun onNot(throwable: String?) {
                updatedialog!!.dismiss()
            }

        })
    }

    fun CodeJson(data: String) {
        if (data == null) {
            return
        }
        try {
            val jo = JSONObject(data)
            val joo = JsonUtil.getjovolue(jo, "data")
            var code = JsonUtil.getvolue(joo, "code")
            var count = JsonUtil.getvolue(joo, "count")
            var machine_number = JsonUtil.getvolue(joo, "machine_number")
            var created_at = JsonUtil.getvolue(joo, "created_at")
            scanList.clear()
            scanAdapter.notifyDataSetChanged()
            codeList.add(0, code)
            codeAdapter.notifyDataSetChanged()
            edithuancun()
            dayingdata(code, count, machine_number, created_at)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }

    override fun onItemLongClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long): Boolean {
        when (parent) {
            LvScan -> {
                var c = context;
                if (c != null) {
                    val dialog = AlertDialog.Builder(c)
                    dialog.setTitle("提示")
                    dialog.setMessage("确定要删除这条交流记录问题?")
                    dialog.setPositiveButton("确定") { dialog, which ->
                        scanList.removeAt(position)
                        scanAdapter.notifyDataSetChanged()
                    }
                    dialog.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                    dialog.show()
                }

            }
        }
        return true
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        when (parent) {
            LvCode -> {
                var c = context;
                if (c != null) {
                    val dialog = AlertDialog.Builder(c)
                    dialog.setTitle("提示")
                    dialog.setMessage("再次打印这个标签?")
                    dialog.setPositiveButton("确定") { _, _ ->
                        updatedialog = Myutil.showupdatedialog(context, "正在获取标签数据数据", false)
                        model.getPcakage(context!!, codeList[position], object : OnUserDataInterface {
                            override fun onUserData(data: String?) {
                                updatedialog!!.dismiss()
                                if (data == null) {
                                    return
                                }
                                try {
                                    val jo = JSONObject(data)
                                    val joo = JsonUtil.getjovolue(jo, "data")
                                    var code = JsonUtil.getvolue(joo, "code")
                                    var count = JsonUtil.getvolue(joo, "count")
                                    var machine_number = JsonUtil.getvolue(joo, "machine_number")
                                    var created_at = JsonUtil.getvolue(joo, "created_at")
                                    dayingdata(code, count, machine_number, created_at)
                                } catch (e: JSONException) {
                                    e.printStackTrace()
                                }
                            }

                            override fun onNot(throwable: String?) {

                            }

                        })

                    }
                    dialog.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                    dialog.show()
                }

            }
        }
    }

    fun dayingdata(s: String, count: String, machine_number: String, time: String) {
        updatedialog = Myutil.showupdatedialog(context, "正在打印标签", false)
        val handle = @SuppressLint("HandlerLeak")
        object : Handler() {
            override fun handleMessage(msg: Message?) {
                msg.let {
                    updatedialog.dismiss()
                    Myutil.MyTost("打印成功")
                }
            }
        }
        val thread = object : Thread() {
            override fun run() {
                dayin(s, count, machine_number, time, handle)
            }
        }
        thread.start()
    }

    fun dayin(pcode: String, count: String, machine_number: String, time: String, handler: Handler) {
        var tscActivity = TSCActivity()
        tscActivity.openport(lanya);
        tscActivity.setup(110, 40, 3, 4, 0, 2, 0);
        tscActivity.clearbuffer();
        tscActivity.sendcommand("\n");
        tscActivity.sendcommand("QRCODE 40,40,L,12,A,0,M2,S7,\"$pcode\"");
        tscActivity.sendcommand("\n");
        val typeface = Typeface.createFromAsset(Myapp.getContext().assets, "宋体-粗体.ttf")
        tscActivity.windowsfont(40, 400, 0, 40, typeface, "包号：");
        tscActivity.windowsfont(150, 400, 0, 40, typeface, pcode);
        tscActivity.windowsfont(400, 40, 0, 40, typeface, "数量：$count");
        tscActivity.windowsfont(400, 110, 0, 40, typeface, "机号：$machine_number");
        tscActivity.windowsfont(400, 180, 0, 40, typeface, "合包时间：$time");
        Thread.sleep(2000);
        tscActivity.printlabel(1, 1);
        tscActivity.closeport()
        val msg = Message.obtain()
        msg.obj = "信息"
        handler.sendMessage(msg)
    }
}